package mainmodel

import (
	"sync"
	"web_server/model"
)

var permMap map[string]int64 = nil
var permMapMut sync.RWMutex

func CheckPerm(perm string) int64 {
	permMapMut.RLock()
	if permMap != nil {
		if v, ok := permMap[perm]; ok {
			permMapMut.RUnlock()
			return v
		} else {
			permMapMut.RUnlock()
			return -1
		}
	}
	permMapMut.RUnlock()
	permMapMut.Lock()
	defer permMapMut.Unlock()
	if permMap != nil {
		if v, ok := permMap[perm]; ok {
			return v
		} else {
			return -1
		}
	}
	permMap = make(map[string]int64)
	var perminfo []struct {
		Id     int64
		Url    string
		Method string
	}
	if err := model.DBSlaveRand().Select(&perminfo, "SELECT id, url, method FROM t_base_permission"); err != nil {
		panic(err)
	}
	for _, v := range perminfo {
		permMap[v.Url+"/"+v.Method] = v.Id
	}
	if v, ok := permMap[perm]; ok {
		return v
	} else {
		return -1
	}

	// permMap = make(map[string]int64)
	// var perminfo []struct {
	// 	Id     int64
	// 	Url    string
	// 	Method string
	// }
	// if err := model.DBSlaveRand().Select(&perminfo, "SELECT id, url, method FROM t_base_permission"); err != nil {
	// 	panic(err)
	// }
	// for _, v := range perminfo {
	// 	permMap[v.Url+"/"+v.Method] = v.Id
	// }
	// if v, ok := permMap[perm]; ok {
	// 	return v
	// } else {
	// 	return -1
	// }
}

func ClearPerm() {
	permMapMut.Lock()
	defer permMapMut.Unlock()
	permMap = nil
}
